import * as request from 'superagent'
import * as config from 'config'
import ms = require("ms");

const appId = config.get<string>('wx.app_id')
const secret = config.get<string>('wx.app_secret')

export type AuthInfo = {
  accessToken: string,
  refreshToken: string,
  openid: string,
  accessExpireAt: Date,
  refreshExpireAt: Date
}

type UserInfo = {
  openid: string,
  nickname: string,
  sex: 1 | 2 | 3,
  language: string,
  city: string,
  province: string,
  country: string,
  headimgurl: string,
  unionid: string
}

export class WechatAuth20 {

  constructor(private readonly appId: string, private readonly secret: string) {
  }


  async getAuthInfo(code: string): Promise<AuthInfo> {
    let t = await request.get('https://api.weixin.qq.com/sns/oauth2/access_token')
      .query({
        appid: this.appId,
        secret: this.secret,
        code,
        grant_type: 'authorization_code'
      })
    console.log('*************00 ',t )

    const {text} = t /*await request.get('https://api.weixin.qq.com/sns/oauth2/access_token')
      .query({
        appid: this.appId,
        secret: this.secret,
        code,
        grant_type: 'authorization_code'
      })*/

    const body = JSON.parse(text)
    if (body.errcode) {
      throw Error(body.errmsg)
    }

    const {
      access_token,
      expires_in,
      refresh_token,
      openid
    } = body

    const accessExpireAt = new Date(Date.now() + expires_in * 1000)
    const refreshExpireAt = new Date(Date.now() + ms('30d'))

    return {
      accessToken: access_token,
      refreshToken: refresh_token,
      openid,
      accessExpireAt, refreshExpireAt
    }

  }

  async getUserInfo(info: AuthInfo): Promise<UserInfo> {

    const {text} = await request.get('https://api.weixin.qq.com/sns/userinfo')
      .query({
        access_token: info.accessToken,
        openid: info.openid,
        scope: 'snsapi_userinfo'
      })

    const body = JSON.parse(text)

    if (body.errcode) {
      throw Error(body.errmsg)
    }

    return body
  }
}


export const wechatAuth = new WechatAuth20(appId, secret)
